
package cartagows.wsframework.wssecurity.policy.model;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.apache.neethi.PolicyComponent;

import cartagows.wsframework.wssecurity.policy.SP11Constants;
import cartagows.wsframework.wssecurity.policy.SP12Constants;
import cartagows.wsframework.wssecurity.policy.SPConstants;

public class RecipientToken extends AbstractSecurityAssertion implements TokenWrapper {
    
    private Token receipientToken;
    
    public RecipientToken(int version) {
        setVersion(version);
    }
   
    public Token getReceipientToken() {
        return receipientToken;
    }

    public void setReceipientToken(Token receipientToken) {
        this.receipientToken = receipientToken;
    }

    public void setToken(Token tok) {
        this.setReceipientToken(tok);
    }

    public QName getName() {
        if ( version == SPConstants.SP_V12) {
            return SP12Constants.RECIPIENT_TOKEN;
        } else {
            return SP11Constants.RECIPIENT_TOKEN;
        }     
    }

    public PolicyComponent normalize() {
        throw new UnsupportedOperationException();
    }

    public void serialize(XMLStreamWriter writer) throws XMLStreamException {
        String localName = getName().getLocalPart();
        String namespaceURI = getName().getNamespaceURI();

        String prefix = writer.getPrefix(namespaceURI);

        if (prefix == null) {
            prefix = getName().getPrefix();
            writer.setPrefix(prefix, namespaceURI);
        }
        
        // <sp:RecipientToken>
        writer.writeStartElement(prefix, localName, namespaceURI);
        
        String pPrefix = writer.getPrefix(SPConstants.POLICY.getNamespaceURI());
        if (pPrefix == null) {
            pPrefix = SPConstants.POLICY.getPrefix();
            writer.setPrefix(pPrefix, SPConstants.POLICY.getNamespaceURI());
        }
        
        // <wsp:Policy>
        writer.writeStartElement(pPrefix, SPConstants.POLICY.getLocalPart(), SPConstants.POLICY.getNamespaceURI());

        Token token = getReceipientToken();
        if (token == null) {
            throw new RuntimeException("RecipientToken doesn't contain any token assertions");
        }
        token.serialize(writer);
        
        // </wsp:Policy>
        writer.writeEndElement();
        
        // </sp:RecipientToken>
        writer.writeEndElement();
    }    
}
